package vy.org.app.page.printlabel.report.instance;

import java.awt.Color;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.vy.dal.dao.ViewVyPrintLabelDAO;
import org.vy.dal.dao.ViewVyPrintLabelDO;
import org.vy.dal.dao.VyPrintLabelReportInstanceDAO;
import org.vy.dal.dao.VySubscriptionTransactionDAO;
import org.vy.dal.dao.VySubscriptionTransactionDO;
import org.vy.dal.dao.lookup.ViewVyLookupCitiesDAO;
import org.vy.dal.dao.lookup.ViewVyLookupCitiesDO;

import vy.org.app.common.Config;

import com.lowagie.text.BadElementException;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Element;
import com.lowagie.text.Font;
import com.lowagie.text.FontFactory;
import com.lowagie.text.PageSize;
import com.lowagie.text.Paragraph;
import com.lowagie.text.Rectangle;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.PdfPCell;
import com.lowagie.text.pdf.PdfPTable;
import com.lowagie.text.pdf.PdfWriter;

public class PrintLabelReportPdf extends ReportInstance {

	public static final String DELIMITER = " AND ";
	private static Map<String, Map<String, ViewVyLookupCitiesDO>> cities = new HashMap<String, Map<String, ViewVyLookupCitiesDO>>();
	private static Map<String, Map<String, ViewVyLookupCitiesDO>> states = new HashMap<String, Map<String, ViewVyLookupCitiesDO>>();
	private static Map<String, ViewVyLookupCitiesDO> countries = new HashMap<String, ViewVyLookupCitiesDO>();
	public static SimpleDateFormat _DTFMT = new SimpleDateFormat("MMM yyyy");
	private static int MAX_COUNT = 12;

	protected PrintLabelReportPdf(Integer reportId) throws Exception {
		super(reportId);
	}

	@Override
	public void run() {
		// parse criteria
		// form query
		// execute query
		// iterate over data and start writing to file
		// after every 100 record check for status not cancelled
		// at end close file
		// read file in bytes and upload to db
		// set the status as completed
		// delete the file
		// remove the instance from manager

		String[] criterias = report.getCriteria().split(DELIMITER);
		String sqlClause = " 1=1 ";
		String country = null;
		for (String term : criterias) {
			String[] val = term.split("=");
			if ("PATRIKA_ID".equals(val[0]))
				sqlClause += DELIMITER + "PATRIKA_ID LIKE " + val[1];
			if ("ceil(datediff(end_date, start_date)/30)".equals(val[0]))
				sqlClause += DELIMITER + "PERIOD_MONTH LIKE " + val[1];
			if ("COUNTRY".equals(val[0])) {
				sqlClause += DELIMITER + "COUNTRY LIKE " + val[1] + " ";
				country = val[1].replaceAll("'", "");
			}
			if ("STATE".equals(val[0]))
				sqlClause += DELIMITER + "STATE_OR_REGION LIKE " + val[1] + " ";
			if("CITY".equals(val[0]))
				sqlClause += DELIMITER + "CITY LIKE " + val[1] +" ";
			if("QUANTITY".equals(val[0]) && "N".equals(val[1])){
				sqlClause += DELIMITER + "QUANTITY > 1 ";
			}else if("QUANTITY".equals(val[0]) && "1".equals(val[1])){
				sqlClause += DELIMITER + "QUANTITY = 1 ";
			}
			// if("WEEK_OFFSET_INDEX".equals(val[0]))
			// sqlClause += DELIMITER + "WEEK_OFFSET_INDEX LIKE '" + val[1]
			// +"' ";
		}
		sqlClause += DELIMITER
				+ " IS_ACTIVE = true AND (EXTRACT(YEAR_MONTH FROM CURRENT_DATE) between EXTRACT(YEAR_MONTH FROM START_DATE) and EXTRACT(YEAR_MONTH FROM END_DATE))";

		try {
			// countries
			List<ViewVyLookupCitiesDO> lstCountry = null;

			if (!"%".equals(country)) {
				ViewVyLookupCitiesDO ctry = ViewVyLookupCitiesDAO
						.findByCountryCode(country);
				lstCountry = new ArrayList<ViewVyLookupCitiesDO>();
				lstCountry.add(ctry);
			} else {
				lstCountry = ViewVyLookupCitiesDAO.findUniqueCountries();
			}
			for (ViewVyLookupCitiesDO dto : lstCountry) {
				countries.put(dto.getCountryCode(), dto);
				List<ViewVyLookupCitiesDO> lstStates = ViewVyLookupCitiesDAO
						.findStateByCountry(dto.getCountryCode());
				Map<String, ViewVyLookupCitiesDO> locState = new HashMap<String, ViewVyLookupCitiesDO>();
				for (ViewVyLookupCitiesDO sto : lstStates) {
					locState.put(sto.getStateCode(), sto);
					List<ViewVyLookupCitiesDO> lstCities = ViewVyLookupCitiesDAO
							.findCitiesByStateAndCountry(sto.getStateCode(),
									dto.getCountryCode());
					Map<String, ViewVyLookupCitiesDO> locCity = new HashMap<String, ViewVyLookupCitiesDO>();
					for (ViewVyLookupCitiesDO cto : lstCities) {
						locCity.put(cto.getCityCode(), cto);
					}
					cities.put(
							dto.getCountryCode() + "->" + sto.getStateCode(),
							locCity);
				}
				states.put(dto.getCountryCode(), locState);
			}

			List<ViewVyPrintLabelDO> results = ViewVyPrintLabelDAO
					.findByParam(sqlClause);
			processResults(results);
			if (instance.getStatus() != ReportStatusEnum.CANCELLED.getId())
				uploadResult();

			instance.setEndTime(new Date());
			VyPrintLabelReportInstanceDAO.updateStatusEndTime(instance);

			remove();
		} catch (Exception e) {
			e.printStackTrace();
			// set status failed
			try {
				instance.setStatus(ReportStatusEnum.FAILED.getId());
				instance.setEndTime(new Date());
				VyPrintLabelReportInstanceDAO.updateStatusEndTime(instance);
			} catch (Exception es) {
				es.printStackTrace();
			}
		}
		remove();
	}

	public void processResults(List<ViewVyPrintLabelDO> results)
			throws IOException, FileNotFoundException, Exception {
		String fileName = Config.getProperty("FILE_PATH")
				+ instance.getReportInstanceId() + ".pdf";
		File file = new File(fileName);
		if (file.exists())
			file.delete();
		file.createNewFile();

		StringWriter fw = new StringWriter();
		Document document = new Document(PageSize.A4, 36, 36, 36, 36);
		PdfWriter pdfWriter = PdfWriter.getInstance(document,
				new FileOutputStream(fileName));
		document.open();
		document.addAuthor("Vihangam Yoga");
		document.addCreator("Vihangam Yoga");
		document.addSubject(report.getReportName() + " "
				+ _DTFMT.format(new Date()));
		document.addCreationDate();
		document.addTitle(report.getReportName() + " "
				+ _DTFMT.format(new Date()));

		try {
			long l = 0;
			Calendar cal = Calendar.getInstance();
			ViewVyPrintLabelDO addr = null;
			int qty = 0;
			String grpId = null;
			PdfPTable mainTable = null;
			if (results != null && !results.isEmpty()) {
				for (ViewVyPrintLabelDO dto : results) {

					// First check for group id
					// Yes - sum up all quantities
					// get the record with label address
					// No - get the current record label address and current
					// quantity
					// if quantity less <= 50 create single block else multiple
					// block
					// each block check for label address language, if hindi
					// print hindi else english

					if (dto.getPrintLabelGroupId() == null
							|| "".equals(dto.getPrintLabelGroupId()))
						continue;

					VySubscriptionTransactionDO subDO = new VySubscriptionTransactionDO();
					subDO.setSubscriptionId(dto.getSubscriptionId());
					int Q = (cal.get(Calendar.MONTH) + 3) / 3;
					String MQY = cal.get(Calendar.MONTH) + "" + Q + ""
							+ cal.get(Calendar.YEAR);
					subDO.setForMQY(Integer.parseInt(MQY));
					subDO.setVyId(dto.getVyId());
					subDO.setAddressId(dto.getAddressId());
					subDO.setIsDispatched(false);
					subDO.setCreatedDate(new Date());
					subDO.setDispatchMode(dto.getDeliveryMode());
					subDO.setReportInstanceId(instance.getReportInstanceId());
					subDO.setComments(dto.getInstruction() != null ? dto
							.getInstruction() : "");
					try {
						subDO = VySubscriptionTransactionDAO.insert(subDO);
						dto.setIsActive(true);
					} catch (Exception e) {
						dto.setIsActive(false);
					}

					if (dto.getPrintLabelGroupId().equals(grpId)) {
						qty += dto.getQuantity();
						if (dto.getIsLabelAddress() == null
								|| dto.getIsLabelAddress() == false)
							addr = null;
						else
							addr = dto;
						continue;
					}
					if (addr != null && grpId != null){
						if(l==0 || l%10 == 0){
							if(mainTable != null)
								document.add(mainTable);
							document.newPage();
							document.setPageCount(document.getPageNumber() + 1);
							mainTable = getTable(document);
						}
						l = print(addr, qty, document, l, mainTable);
					}

					qty = dto.getQuantity();
					if (dto.getIsLabelAddress() == null
							|| dto.getIsLabelAddress() == false)
						addr = null;
					else
						addr = dto;
					grpId = dto.getPrintLabelGroupId();

					if (l % 100 == 0
							&& ReportStatusEnum.CANCELLED.getId() == instance
									.getStatus()) {
						fw.flush();
						fw.close();
						return;
					}
				}

				for (ViewVyPrintLabelDO dto : results) {

					// First check for group id
					// Yes - sum up all quantities
					// get the record with label address
					// No - get the current record label address and current
					// quantity
					// if quantity less <= 50 create single block else multiple
					// block
					// each block check for label address language, if hindi
					// print hindi else english

					if (dto.getPrintLabelGroupId() != null
							|| !dto.getIsActive())
						continue;

					VySubscriptionTransactionDO subDO = new VySubscriptionTransactionDO();
					subDO.setSubscriptionId(dto.getSubscriptionId());
					int Q = (cal.get(Calendar.MONTH) + 3) / 3;
					String MQY = cal.get(Calendar.MONTH) + "" + Q + ""
							+ cal.get(Calendar.YEAR);
					subDO.setForMQY(Integer.parseInt(MQY));
					subDO.setVyId(dto.getVyId());
					subDO.setAddressId(dto.getAddressId());
					subDO.setIsDispatched(false);
					subDO.setCreatedDate(new Date());
					subDO.setDispatchMode(dto.getDeliveryMode());
					subDO.setReportInstanceId(instance.getReportInstanceId());
					subDO.setComments(dto.getInstruction() != null ? dto
							.getInstruction() : "");
					try {
						subDO = VySubscriptionTransactionDAO.insert(subDO);
						dto.setIsActive(true);
					} catch (Exception e) {
						// dto.setIsActive(false);
						continue;
					}

					qty = dto.getQuantity();
					if(l==0 || l%10 == 0){
						if(mainTable != null)
							document.add(mainTable);
						document.newPage();
						document.setPageCount(document.getPageNumber() + 1);
						mainTable = getTable(document);
					}
					l = print(dto, qty, document, l, mainTable);
					if (l % 100 == 0
							&& ReportStatusEnum.CANCELLED.getId() == instance
									.getStatus()) {
						fw.flush();
						fw.close();
						return;
					}
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		instance.setStatus(ReportStatusEnum.SUCCESS.getId());
		fw.close();
		document.close();
		pdfWriter.flush();
		pdfWriter.close();
	}

	private long print(ViewVyPrintLabelDO addr, int qty, Document doc,
			long l, PdfPTable tbl) throws IOException, BadElementException, DocumentException {

		if (l == 0 || l % 2 == 0){
			//fw.append("<tr>");
		}
		if (l % 2 == 0) {
			//fw.append("</tr>");
		}
		int q = (qty <= 50) ? qty : qty - 50;
		String id = (addr.getPrintLabelGroupId() == null) ? addr
				.getSubscriptionId() : addr.getPrintLabelGroupId();

		PdfPTable child = new PdfPTable(2);
		//int[] wds = {250, 250};
		//child.setWidths(wds);
		child.setWidthPercentage(100);
		child.getDefaultCell().setBorder(Rectangle.NO_BORDER);
		child.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT);
		child.getDefaultCell().setVerticalAlignment(Element.ALIGN_TOP);
		child.getDefaultCell().setPadding(0);
		
		//child.setConvert2pdfptable(true);
		
//		fw.append("<td valign='top'><table width='100%' cellpadding='0' cellspacing='0' border='0'>");
		PdfPCell r1c1 = new PdfPCell();
		PdfPCell r1c2 = new PdfPCell();
		r1c1.addElement(new Paragraph("ID : " + id, info));
		r1c1.setBorderWidth(0);
		r1c2.addElement(new Paragraph("Qty : " + q, info));
		r1c2.setBorderWidth(0);
		child.addCell(r1c1);
		child.addCell(r1c2);
		
//		fw.append("<tr><td class='lt info'>ID : " + id + "</td><td class='rt info'>Qty : " + q + "</td></tr>");
		if ("hi".equals(addr.getPrintLanguage())) {
			if (addr.getRegionalLangName() != null
					&& !"".equals(addr.getRegionalLangName().trim())){
				PdfPCell r2c1 = new PdfPCell();
				r2c1.setColspan(2);
				Paragraph  ph = new Paragraph(parse(addr.getRegionalLangName()),kdk010);
				r2c1.addElement(ph);
				r2c1.setBorderWidth(0);
				child.addCell(r2c1);
				//fw.append("<tr><td colspan='2' class='kd010'>" + parse(addr.getRegionalLangName()) + "</td></tr>");
			}
			if (addr.getCoName() != null && !"".equals(addr.getCoName().trim())){
				PdfPCell r3c1 = new PdfPCell();
				r3c1.setColspan(2);
				Paragraph ph = new Paragraph();
				ph.add(new Paragraph(addr.getNamePrefix() + " ", lbl));
				ph.add(new Paragraph(parse(addr.getCoName()), kdk010));
				r3c1.setBorderWidth(0);
				r3c1.addElement(ph);
				child.addCell(r3c1);
				//fw.append("<tr><td colspan='2'>" + addr.getNamePrefix() + " <span class='kd010'>" + parse(addr.getCoName()) + "</span></td></tr>");
			}

			if (addr.getStreetHindi1() != null
					&& !"".equals(addr.getStreetHindi1().trim())){
				PdfPCell r4c1 = new PdfPCell();
				r4c1.setColspan(2);
				Paragraph ph = new Paragraph(parse(addr.getStreetHindi1()),kdk010);
				r4c1.addElement(ph);
				r4c1.setBorderWidth(0);
				child.addCell(r4c1);
				//fw.append("<tr><td class='kd010' colspan='2'>" + parse(addr.getStreetHindi1()) + "</td></tr>");
			}
			else if (addr.getStreet1() != null
					&& !"".equals(addr.getStreet1().trim())){
				PdfPCell r5c1 = new PdfPCell();
				r5c1.setColspan(2);
				Paragraph ph = new Paragraph(parse(addr.getStreet1()), lbl);
				r5c1.addElement(ph);
				r5c1.setBorderWidth(0);
				child.addCell(r5c1);
				//fw.append("<tr><td colspan='2'>" + parse(addr.getStreet1()) + "</td></tr>");
			}
			if (addr.getStreetHindi2() != null
					&& !"".equals(addr.getStreetHindi2().trim())){
				PdfPCell r6c1 = new PdfPCell();
				r6c1.setColspan(2);
				Paragraph ph = new Paragraph(parse(addr.getStreetHindi2()),kdk010);
				r6c1.addElement(ph);
				r6c1.setBorderWidth(0);
				child.addCell(r6c1);
				//fw.append("<tr><td class='kd010' colspan='2'>" + parse(addr.getStreetHindi2()) + "</td></tr>");
			}
			else if (addr.getStreet2() != null
					&& !"".equals(addr.getStreet2().trim())){
				PdfPCell r7c1 = new PdfPCell();
				r7c1.setColspan(2);
				Paragraph ph = new Paragraph(parse(addr.getStreet2()), lbl);
				r7c1.addElement(ph);
				r7c1.setBorderWidth(0);
				child.addCell(r7c1);
				//fw.append("<tr><td colspan='2'>" + parse(addr.getStreet2())	+ "</td></tr>");
			}
			if (addr.getCity() != null && !"".equals(addr.getCity().trim())) {
				PdfPCell r8c1 = new PdfPCell();
				r8c1.setColspan(2);
				Paragraph ph = new Paragraph(getCity(addr.getCountry(), addr.getStateOrRegion(), addr.getCity(), true) 
						+ " " + getState(addr.getStateOrRegion(), addr.getCountry(), true) + " - "
						+ (addr.getZip() != null ? addr.getZip() : ""), kdk010);
				r8c1.addElement(ph);
				r8c1.setBorderWidth(0);
				child.addCell(r8c1);
/*				fw.append("<tr><td class='kd010' colspan='2'>"
						+ getCity(addr.getCountry(), addr.getStateOrRegion(),
								addr.getCity(), true)
						+ " "
						+ getState(addr.getStateOrRegion(), addr.getCountry(),
								true) + " - "
						+ (addr.getZip() != null ? addr.getZip() : "")
						+ "</td></tr>");
*/
			} else if (addr.getStateOrRegion() != null
				&& !"".equals(addr.getStateOrRegion().trim())) {
				PdfPCell r9c1 = new PdfPCell();
				r9c1.setColspan(2);
				Paragraph ph = new Paragraph(getState(addr.getStateOrRegion(), addr.getCountry(),
						true) + " - " + (addr.getZip() != null ? addr.getZip() : ""), kdk010);
				r9c1.addElement(ph);
				r9c1.setBorderWidth(0);
				child.addCell(r9c1);
/*					fw.append("<tr><td class='kd010' colspan='2'>"
						+ getState(addr.getStateOrRegion(), addr.getCountry(),
								true) + " - "
						+ (addr.getZip() != null ? addr.getZip() : "")
						+ "</td></tr>");
*/
			}
			if (addr.getCountry() != null
				&& !"".equals(addr.getCountry().trim())) {
				PdfPCell r10c1 = new PdfPCell();
				r10c1.setColspan(2);
				Paragraph ph = new Paragraph(getCountry(addr.getCountry(), true), kdk010);
				r10c1.addElement(ph);
				r10c1.setBorderWidth(0);
				child.addCell(r10c1);
				//fw.append("<tr><td colspan='2' class='kd010'>" + getCountry(addr.getCountry(), true) + "</td></tr>");
			}
		} else {
			if (addr.getFirstName() != null
					&& !"".equals(addr.getFirstName().trim())){
				PdfPCell rc1 = new PdfPCell();
				rc1.setColspan(2);
				rc1.addElement(new Paragraph(addr.getFirstName()
						+ (addr.getLastName() != null
								&& !"".equals(addr.getLastName()) ? ", "
								+ addr.getLastName() : ""), lbl));
				rc1.setBorderWidth(0);
				child.addCell(rc1);
/*				fw.append("<tr><td colspan='2'>"
						+ addr.getFirstName()
						+ (addr.getLastName() != null
								&& !"".equals(addr.getLastName()) ? ", "
								+ addr.getLastName() : "") + "</td></tr>");
*/
			}
			if (addr.getStreet1() != null
					&& !"".equals(addr.getStreet1().trim())){
				PdfPCell rc1 = new PdfPCell();
				rc1.setColspan(2);
				rc1.addElement(new Paragraph(parse(addr.getStreet1()), lbl));
				rc1.setBorderWidth(0);
				child.addCell(rc1);
				//fw.append("<tr><td colspan='2'>" + parse(addr.getStreet1())	+ "</td></tr>");
			}
			if (addr.getStreet2() != null
					&& !"".equals(addr.getStreet2().trim())){
				PdfPCell rc1 = new PdfPCell();
				rc1.setColspan(2);
				rc1.addElement(new Paragraph(parse(addr.getStreet2()), lbl));
				rc1.setBorderWidth(0);
				child.addCell(rc1);
				//fw.append("<tr><td colspan='2'>" + parse(addr.getStreet2())	+ "</td></tr>");
			}
			if (addr.getCity() != null && !"".equals(addr.getCity().trim())) {
				PdfPCell rc1 = new PdfPCell();
				rc1.setColspan(2);
				rc1.setBorderWidth(0);
				rc1.addElement(new Paragraph(getCity(addr.getCountry(), addr.getStateOrRegion(),
								addr.getCity(), false)
						+ " "
						+ getState(addr.getStateOrRegion(), addr.getCountry(),
								false) + " - "
						+ (addr.getZip() != null ? addr.getZip() : ""), lbl));
				child.addCell(rc1);
/*				fw.append("<tr><td colspan='2'>"
						+ getCity(addr.getCountry(), addr.getStateOrRegion(),
								addr.getCity(), false)
						+ " "
						+ getState(addr.getStateOrRegion(), addr.getCountry(),
								false) + " - "
						+ (addr.getZip() != null ? addr.getZip() : "")
						+ "</td></tr>");
*/
			} else if (addr.getStateOrRegion() != null
					&& !"".equals(addr.getStateOrRegion().trim())) {
				PdfPCell rc1 = new PdfPCell();
				rc1.setColspan(2);
				rc1.setBorderWidth(0);
				rc1.addElement(new Paragraph(getState(addr.getStateOrRegion(), addr.getCountry(),
								false) + " - "
						+ (addr.getZip() != null ? addr.getZip() : ""), lbl));
				child.addCell(rc1);
/*				fw.append("<tr><td colspan='2'>"
						+ getState(addr.getStateOrRegion(), addr.getCountry(),
								false) + " - "
						+ (addr.getZip() != null ? addr.getZip() : "")
						+ "</td></tr>");
*/			}
			if (addr.getCountry() != null
					&& !"".equals(addr.getCountry().trim())) {
				PdfPCell rc1 = new PdfPCell();
				rc1.setColspan(2);
				rc1.setBorderWidth(0);
				rc1.addElement(new Paragraph(getCountry(addr.getCountry(), false), lbl));
				child.addCell(rc1);
				//fw.append("<tr><td colspan='2'>" + getCountry(addr.getCountry(), false) + "</td></tr>");
			}
		}
		if (addr.getInstruction() != null){
			PdfPCell rc1 = new PdfPCell();
			rc1.setColspan(2);
			rc1.setBorderWidth(0);
			rc1.addElement(new Paragraph(parse(addr.getInstruction()), lbl));
			child.addCell(rc1);
			//fw.append("<tr><td colspan='2' class='info'>" + parse(addr.getInstruction()) + "</td></tr>");
		}

//		fw.append("</table></td>");
		PdfPCell cell1 = new PdfPCell();
		cell1.addElement(child);
		//cell1.setWidth("50%");
		cell1.setBorderWidth(1);
		tbl.addCell(cell1);

		l++;

		if (qty <= 50)
			return l;
		else{
			if(l==0 || l%10 == 0){
				doc.add(tbl);
				doc.newPage();
				doc.setPageCount(doc.getPageNumber() + 1);
				tbl = getTable(doc);
			}
			return print(addr, qty - 50, doc, l, tbl);
		}
	}

	private boolean uploadResult() {
		try {
			String fileName = Config.getProperty("FILE_PATH")
					+ instance.getReportInstanceId() + ".pdf";
			File file = new File(fileName);
			BufferedReader fw = new BufferedReader(new FileReader(file));
			StringBuilder sb = new StringBuilder();
			String line = fw.readLine();
			while (line != null) {
				sb.append(line);
				line = fw.readLine();
			}
			ByteArrayInputStream by = new ByteArrayInputStream(sb.toString()
					.getBytes());
			int cnt = VyPrintLabelReportInstanceDAO.updateData(
					instance.getReportInstanceId(), by);
			if (cnt > 0) {
				instance.setStatus(ReportStatusEnum.SUCCESS.getId());
			} else {
				instance.setStatus(ReportStatusEnum.FAILED.getId());
			}

			file.delete();

			return (cnt > 0);
		} catch (Exception e) {
			return false;
		}
	}

	private String getCity(String country, String state, String city,
			boolean flg) {
		if (cities.containsKey(country + "->" + state)) {
			Map<String, ViewVyLookupCitiesDO> map = cities.get(country + "->"
					+ state);
			ViewVyLookupCitiesDO dto = map.get(city);
			if (dto == null)
				return "";
			if (dto.getCityHindiName() != null && flg)
				return parse(dto.getCityHindiName());
			else
				return dto.getCityName();
		} else
			return "";
	}

	private String getState(String state, String country, boolean flg) {
		if (states.containsKey(country)) {
			Map<String, ViewVyLookupCitiesDO> map = states.get(country);
			ViewVyLookupCitiesDO dto = map.get(state);
			if (dto == null)
				return "";
			if (dto.getStateHindiName() != null && flg)
				return parse(dto.getStateHindiName());
			else
				return dto.getStateName();
		} else
			return "";
	}

	private String getCountry(String country, boolean flg) {
		if (countries.containsKey(country)) {
			ViewVyLookupCitiesDO dto = countries.get(country);
			if (dto == null)
				return "";
			if (dto.getCountryHindiName() != null && flg)
				return parse(dto.getCountryHindiName());
			else
				return dto.getCountryName();
		} else
			return "";
	}

	private String parse(String inp) {
		inp = inp.replaceAll("&", "&amp;").replaceAll("<", "&lt;")
				.replaceAll(">", "&gt;");
		return inp;
	}
	
	public PdfPTable getTable(Document doc) throws DocumentException, BadElementException {
		PdfPTable tbl = new PdfPTable(2);
		tbl.setWidthPercentage(100);
		tbl.getDefaultCell().setBorder(Rectangle.NO_BORDER);
		tbl.getDefaultCell().setHorizontalAlignment(Element.ALIGN_LEFT);
		tbl.getDefaultCell().setVerticalAlignment(Element.ALIGN_TOP);
		tbl.getDefaultCell().setPadding(5);
		tbl.getDefaultCell().setPaddingRight(10);
		return tbl;
	}

	//public static final Font kdk010;
	public static final Font kdk010;
	public static final Font info;
	public static final Font lbl;
	public static final Font name;
	
	static {
		BaseFont timesbf = null;
		BaseFont infobf = null;
		try {
			timesbf = BaseFont.createFont(
					"C:/vyrepo/VyManagement/WebContent/fonts/K010.TTF",
					BaseFont.WINANSI, BaseFont.EMBEDDED, true);
		} catch (DocumentException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		kdk010 = new Font(timesbf, 14);
		info = FontFactory.getFont(FontFactory.HELVETICA, 7, Color.GRAY);
		lbl = FontFactory.getFont(FontFactory.HELVETICA, 10, Color.BLACK);
		name = FontFactory.getFont(FontFactory.HELVETICA_BOLD, 10, Color.BLACK);
	}
}
